package com.app.myApp.control;


import com.app.myApp.dao.UserInfoDAO;
import com.app.myApp.dataobject.UserInfoDO;
import com.app.myApp.model.EmailReq;
import com.app.myApp.model.Response;
import com.app.myApp.model.User;
import com.app.myApp.model.UserInfo;
import com.app.myApp.service.AvatarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserInfoController {

    @Autowired
    private UserInfoDAO userInfoDAO;

    @Autowired
    private AvatarService avatarService;

    @PostMapping("/users/getUserInformation")
    public ResponseEntity<Response> getUserInformation(@RequestBody User user) {
        String email = user.getEmail();
        // 1. 校验参数
        if (!StringUtils.hasText(email)) {
            return new ResponseEntity<>(Response.error("参数不能为空"), HttpStatus.BAD_REQUEST);
        }

        UserInfoDO userInfo = userInfoDAO.selectByEmail(email);
        if (userInfo!=null){
            return new ResponseEntity<>(Response.success(userInfo), HttpStatus.OK);
        }
        return new ResponseEntity<>(Response.error("查询个人信息失败"),HttpStatus.BAD_REQUEST);

    }

    @PostMapping("/users/editUserInformation")
    public ResponseEntity<Response> editUserInformation(@RequestBody UserInfo userInfo) {
        String email = userInfo.getEmail();
        // 1. 校验参数
        if (!StringUtils.hasText(email)) {
            return new ResponseEntity<>(Response.error("参数不能为空"), HttpStatus.BAD_REQUEST);
        }

        UserInfoDO userInfoDO = new UserInfoDO();
        userInfoDO.setUserName(userInfoDO.getUserName());
        userInfoDO.setEmail(userInfo.getEmail());
        userInfoDO.setGender(userInfo.getGender());
        userInfoDO.setPhone(userInfo.getPhone());
        int rows = userInfoDAO.updateByEmail(userInfoDO);
        if (rows>0){
            return new ResponseEntity<>(Response.success(userInfo), HttpStatus.OK);
        }
        return new ResponseEntity<>(Response.error("修改个人信息失败"),HttpStatus.BAD_REQUEST);

    }

    @PostMapping("/avatar/upload")
    public ResponseEntity<Response> uploadAvatar(// 用 @RequestParam 接收用户ID（前端FormData中append的"userId"）
                                                 @RequestParam("email") String email,
                                                 // 用 MultipartFile 接收文件，@RequestParam("file") 对应前端FormData的"file"
                                                 @RequestParam("file") MultipartFile file) {
        try {
             if (avatarService.uploadAvatar(email,file)){
                 return new ResponseEntity<>(Response.success(userInfoDAO.selectByEmail(email)), HttpStatus.OK);
             }else {
                 return new ResponseEntity<>(Response.error("修改个人头像失败"),HttpStatus.BAD_REQUEST);
             }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/user/getAvatar")
    public ResponseEntity<Response> getAvatar(@RequestParam("email") String email) {
        UserInfoDO userInfoDO =  userInfoDAO.selectByEmail(email);
        if (userInfoDO!=null){
            return new ResponseEntity<>(Response.success(userInfoDO), HttpStatus.OK);
        }
        return new ResponseEntity<>(Response.error("查询个人头像失败"),HttpStatus.BAD_REQUEST);
    }

    @PostMapping("/avatar/delete")
    public ResponseEntity<Response> getAvatar(@RequestBody UserInfo userInfo) {
        String avatarUrl = userInfo.getAvatarUrl();
        String email = userInfo.getEmail();

        Map<String, Object> response = new HashMap<>();
        try {
            if (avatarUrl == null || avatarUrl.isEmpty()|| avatarUrl.equals("https://love-think-1355440206.cos.ap-shanghai.myqcloud.com/avatars/768a9281-6b6c-4efb-a73e-72845206a16a.png")) {
                return new ResponseEntity<>(Response.error("失败"), HttpStatus.OK);
            }

            boolean success = avatarService.deleteAvatar(email, avatarUrl);

            if (success) {
                response.put("success", true);
                response.put("message", "头像删除成功");
                return new ResponseEntity<>(Response.success(response), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(Response.error("失败"), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (IllegalArgumentException e) {
            return new ResponseEntity<>(Response.error("失败"), HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("失败"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
